/**
 * author wen
 * cunyu
 * email wjd_13@hotmail.com
 */
package com.cunyu.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 错误信息转发给试图层
 * @author win
 * 2019/04/19-11:10
 */
public class ExeceptionHandlerImp implements HandlerExceptionResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExeceptionHandlerImp.class) ;

    /**
     * 如果在 controller 中指定的 视图 地址，在page 中找不到，那么此时的抛出 500 异常
     * 此时的异常是无法捕获的。
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception e) {
        boolean k = true;
        if(handler != null){
            // 应该是服务器内部错误
            LOGGER.error("error from "+ handler.getClass().getSimpleName(),e);
            k = false ;
        }

        ModelAndView model = new ModelAndView();
        model.getModel().put("req",request) ;
        model.getModel().put("res",response) ;
        model.getModel().put("ex",e) ;

        if( k ){
            model.setViewName("404");
            return model;
        }

        model.setViewName("500");
        return model;
    }

}
